<template>
  <div class="app-container">
    <el-tabs v-model="dataIndex" type="border-card" stretch>
      <el-tab-pane label="驱动" name="驱动">
        <el-tree
          :data="treeData"
          :props="defaultProps"
          @node-click="handleNodeClick"
        ></el-tree>
      </el-tab-pane>
      <el-tab-pane label="数据源" name="数据源">
        <el-tree
          :data="dataOrigin"
          :props="dataOriginProps"
          @node-click="handleNodeTable"
        ></el-tree>
      </el-tab-pane>
      <el-tab-pane label="数据分析" name="数据分析">
        <el-menu default-active="2" class="el-menu-vertical-demo">
          <el-menu-item index="1">
            <i class="el-icon-s-grid"></i>
            <span slot="title">数据集</span>
          </el-menu-item>

          <el-menu-item index="2">
            <i class="el-icon-s-data"></i>
            <span slot="title">图表</span>
          </el-menu-item>

          <el-menu-item index="3" @click="textDialogVisible = true">
            <i class="el-icon-s-order"></i>
            <span slot="title">看板</span>
          </el-menu-item>
        </el-menu>
      </el-tab-pane>
    </el-tabs>

    <el-tabs
      v-show="dataIndex !== '数据分析'"
      v-model="editableTabsValue"
      type="card"
      closable
      @tab-remove="removeTab"
      style="width: 100%"
    >
      <el-tab-pane
        v-for="item in editableTabs"
        :key="item.id"
        :label="item.driverName"
        :name="item.driverName"
      >
        <el-row style="padding: 0 20px 10px">
          <el-col>
            <el-input
              clearable
              style="width: 260px"
              v-model="form.host"
              autocomplete="off"
            ></el-input>
            <el-button style="margin-left: 20px" type="primary">查询</el-button>
          </el-col>

          <div style="float: right">
            <el-button
              @click="drawer = true"
              type="primary"
              style="margin-left: 16px"
            >
              SQL工作台
            </el-button>
            <el-button type="primary" @click="editSql('添加')">添加</el-button>
            <!-- <el-button type="primary">编辑</el-button>
            <el-button type="primary">查看</el-button> -->
            <el-button type="primary">导出</el-button>
            <!-- <el-button type="danger" @click="deleteData">删除</el-button> -->
          </div>
        </el-row>
        <el-table
          ref="multipleTable"
          :data="tableData"
          style="width: 100%"
          :header-cell-style="{ background: '#f0f8ff', color: '#333333' }"
          border
          @selection-change="handleSelectionChange"
          max-height="700"
          height="700"
          highlight-current-row
        >
          <el-table-column type="selection" width="55"> </el-table-column>
          <el-table-column prop="TABLE_NAME" label="数据库连接id">
          </el-table-column>
          <el-table-column prop="TABLE_CAT" label="所属目录"></el-table-column>
          <el-table-column prop="TABLE_TYPE" label="表类型"></el-table-column>
          <el-table-column prop="REMARKS" label="表备注信息"></el-table-column>
          <el-table-column fixed="right" label="操作" width="140">
            <template slot-scope="scope">
              <el-button type="text" @click="editSql('编辑', scope.row)"
                >编辑</el-button
              >
              <el-button
                style="color: red"
                @click="deleteData(scope.row, scope.$index, tableData)"
                type="text"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>
      </el-tab-pane>
    </el-tabs>

    <!-- 编辑可视化图表位置 -->
    <!-- <el-container>
      <el-aside width="auto">
        <router-link
          tag="li"
          class="menu_item"
          to="/guide/chart/line"
          active-class="active"
        >
          <chart-menu-icon :icon-index="1"></chart-menu-icon>
        </router-link>
        <router-link
          tag="li"
          class="menu_item"
          to="/guide/chart/bar"
          active-class="active"
        >
          <chart-menu-icon :icon-index="2"></chart-menu-icon>
        </router-link>
        <router-link
          tag="li"
          class="menu_item"
          to="/guide/chart/pie"
          active-class="active"
        >
          <chart-menu-icon :icon-index="5"></chart-menu-icon>
        </router-link>
      </el-aside>
      <el-main class="editor_main" style="height: 100%">
        <router-view></router-view>
      </el-main>
    </el-container> -->

    <el-dialog
      :close-on-click-modal="false"
      center
      title="新建链接"
      width="50%"
      :visible.sync="newConstruction"
    >
      <el-form :model="form" :rules="rules" ref="ruleForm" label-width="100px">
        <el-form-item label="链接名" prop="connectionName">
          <el-input v-model="form.connectionName" autocomplete="off"></el-input>
        </el-form-item>
        <!-- <el-form-item label="驱动id" prop="driverId">
          <el-input v-model="form.driverId" autocomplete="off"></el-input>
        </el-form-item> -->
        <el-form-item label="主机" prop="host">
          <el-input v-model="form.host" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="端口号" prop="port">
          <el-input v-model.number="form.port" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="用户名" prop="userName">
          <el-input v-model="form.userName" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="form.password" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="库名" prop="schemaName">
          <el-input v-model="form.schemaName" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="newConstruction = false">取 消</el-button>
        <el-button type="primary" @click="okNewConstruction('ruleForm')"
          >确 定</el-button
        >
      </div>
    </el-dialog>

    <el-dialog
      :close-on-click-modal="false"
      title="富文本"
      :visible.sync="textDialogVisible"
      width="90%"
      :before-close="handleClose"
    >
      <tinymce v-model="content" :height="400" />
      <span slot="footer" class="dialog-footer">
        <el-button @click="textDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="textTinymce">确 定</el-button>
      </span>
    </el-dialog>

    <el-dialog
      :close-on-click-modal="false"
      center
      title="选择可用链接"
      :visible.sync="selectDatadialogTableVisible"
      width="60%"
    >
      <el-table :data="usableDataList" max-height="300">
        <el-table-column width="80" label="选择">
          <template slot-scope="scope">
            <el-radio
              :label="scope.row.id"
              v-model="radio"
              @click.native.prevent="selectRadio(scope.row)"
              ><span></span
            ></el-radio>
          </template>
        </el-table-column>
        <el-table-column property="id" label="连接id"></el-table-column>
        <el-table-column
          property="connectionName"
          label="连接名"
        ></el-table-column>
        <el-table-column property="driverId" label="驱动id"></el-table-column>
        <el-table-column property="host" label="主机"></el-table-column>
        <el-table-column property="port" label="端口号"></el-table-column>
        <el-table-column property="userName" label="用户名"></el-table-column>
        <el-table-column property="password" label="密码"></el-table-column>
        <el-table-column property="schemaName" label="库名"></el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button style="color: red" @click="remove(scope.row)" type="text"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>

    <el-drawer
      title="我是标题"
      close-on-press-escape
      direction="btt"
      :visible.sync="drawer"
      :with-header="false"
      :size="size"
      :wrapperClosable="false"
    >
      <Codemirror @operation="operation" @close="closedrawer"></Codemirror>
      <el-table
        :data="sqltableData"
        style="width: 100%"
        :header-cell-style="{ background: '#f0f8ff', color: '#333333' }"
        border
        height="280"
        highlight-current-row
      >
        <el-table-column label="数据库连接id">
          <template slot-scope="scope">
            <span>{{ scope.row["connection.connection_name"] }}</span>
          </template>
        </el-table-column>
        <el-table-column label="所属目录">
          <template slot-scope="scope">
            <span>{{ scope.row["connection.host"] }}</span>
          </template>
        </el-table-column>
        <el-table-column label="表类型">
          <template slot-scope="scope">
            <span>{{ scope.row["connection.schema_name"] }}</span>
          </template>
        </el-table-column>
        <el-table-column label="表备注信息">
          <template slot-scope="scope">
            <span>{{ scope.row["connection.user_name"] }}</span>
          </template>
        </el-table-column>
      </el-table>
    </el-drawer>
  </div>
</template>

<script>
import Tinymce from "@/components/Tinymce";
import Codemirror from "./components/codemirror";
import { getList } from "@/api/data";
import axios from "axios";
export default {
  name: "Guide",
  components: { Tinymce, Codemirror },
  data() {
    return {
      BASE_URL: "http://www.septic-tank.cn:8888/auto_report/",
      drawerName: "",
      sqltableData: [],
      databaseID: 0,
      dataIndex: "驱动",
      dataOrigin: [],
      dataOriginProps: {
        children: "children",
        label: "REMARKS",
      },
      size: "600px",
      drawer: false,
      tableData: [],
      usableDataList: [],
      radio: 0,
      textDialogVisible: false,
      selectDatadialogTableVisible: false,
      content: "",
      newConstruction: false,
      multipleSelection: [],
      form: {
        connectionName: "mySql本地连接",
        driverId: 1,
        host: "139.196.36.157",
        port: 3306,
        userName: "report",
        password: "abcd1234",
        schemaName: "auto_report",
      },

      rules: {
        connectionName: [
          { required: true, message: "请输入链接名", trigger: "blur" },
        ],
        host: [{ required: true, message: "请输入主机", trigger: "blur" }],
        port: [{ required: true, message: "请输入端口号", trigger: "blur" }],
        userName: [
          { required: true, message: "请输入用户名", trigger: "blur" },
        ],
        password: [{ required: true, message: "请输入密码", trigger: "blur" }],
        schemaName: [
          { required: true, message: "请输入库名", trigger: "blur" },
        ],
      },
      treeData: [],
      editableTabs: [],
      editableTabsValue: "1",
      defaultProps: {
        children: "children",
        label: "driverName",
      },
      listQuery: {
        page: 1,
        limit: 10,
      },
      tabIndex: 0,
    };
  },

  created() {
    this.getList();
  },

  methods: {
    remove(row) {
      axios
        .get(this.BASE_URL + "dataSource/delete", {
          params: { id: row.id },
        })
        .then((res) => {});
    },

    textTinymce() {
      console.log(this.content);
    },
    operation(data) {
      console.log(this.drawerName);
      switch (this.drawerName) {
        case "编辑":
          axios
            .get(this.BASE_URL + "exe/dql", {
              params: { connId: this.database, sql: data },
            })
            .then((res) => {
              // this.tableData = res.data.data.tableInfo;
              switch (res.data.code) {
                case "00000":
                  console.log(JSON.parse(res.data.data.result));
                  this.sqltableData = JSON.parse(res.data.data.result);
                  this.$message.success("处理成功");
                  break;
                case "20001":
                  this.$message.error("参数错误");
                  break;
                case "30001":
                  this.$message.error("数据库连接失败");
                  break;
                case "30103":
                  this.$message.error("数据库连接不存在");
                  break;
                case "31001":
                  this.$message.error("驱动信息不存在");
                  break;
                case "30004":
                  this.$message.error("不支持的db类型");
                  break;
                case "99999":
                  this.$message.error("系统错误");
                  break;
              }
            });
          break;
        case "添加":
          axios
            .get(this.BASE_URL + "exe/ddl", {
              params: { connId: this.database, sql: data },
            })
            .then((res) => {
              switch (res.data.code) {
                case "00000":
                  console.log(JSON.parse(res.data.data.result));
                  this.sqltableData = JSON.parse(res.data.data.result);
                  this.$message.success("处理成功");
                  break;
                case "20001":
                  this.$message.error("参数错误");
                  break;
                case "30001":
                  this.$message.error("数据库连接失败");
                  break;
                case "30103":
                  this.$message.error("数据库连接不存在");
                  break;
                case "31001":
                  this.$message.error("驱动信息不存在");
                  break;
                case "30004":
                  this.$message.error("不支持的db类型");
                  break;
                case "99999":
                  this.$message.error("系统错误");
                  break;
              }
            });
          break;
      }
      let query = {
        connId: this.database,
        sql: data,
      };
    },

    editSql(name, row) {
      this.drawerName = name;
      switch (name) {
        case "添加":
          break;
        case "编辑":
          break;
      }
      this.drawer = true;
      // axios
      //   .post(this.BASE_URL + "exe/ddl", {
      //     params: { connId: this.database, tableName: row.TABLE_NAME },
      //   })
      //   .then((res) => {

      //   });
    },

    handleNodeTable(row) {
      axios
        .get(this.BASE_URL + "baseInfo/columnsInfo", {
          params: { connId: this.database, tableName: row.TABLE_NAME },
        })
        .then((res) => {
          ++this.tabIndex;
          this.tableData = res.data.data.columnsInfo;
          let newTabName = `${this.tabIndex}:${row.REMARKS}`;
          this.editableTabs.push({
            driverName: newTabName,
            id: this.tabIndex,
          });
          this.editableTabsValue = newTabName;
        });
    },

    closedrawer() {
      this.drawer = false;
    },
    selectRadio(row) {
      this.database = row.id;
      this.selectDatadialogTableVisible = false;
      axios
        .get(this.BASE_URL + "baseInfo/showTables", {
          params: { connId: row.id },
        })
        .then((res) => {
          this.dataOrigin = res.data.data.tableInfo;
          this.dataIndex = "数据源";
          // let newTabName = `${++this.tabIndex}:${row.connectionName}`;
          // this.editableTabs.push({
          //   driverName: newTabName,
          //   id: this.tabIndex,
          // });
          // this.editableTabsValue = newTabName;
        });
    },

    handleClose(done) {
      this.$confirm("确认关闭？")
        .then((_) => {
          done();
        })
        .catch((_) => {});
    },

    look(row) {
      console.log(row);
      axios
        .post(this.BASE_URL + "connection/detail", { id: row.id })
        .then((res) => {
          if (res.data.code === "00000") {
            // this.selectDatadialogTableVisible = true;
            // this.usableDataList = res.data.data;
          } else {
            this.$message.error("查询可用数据详情错误请联系开发者");
          }
        });
    },

    deleteData(row, index) {
      this.$confirm("此操作将永久删除该文件, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.$message({
            type: "success",
            message: "删除成功!",
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
      // this.$refs.multipleTable.clearSelection();
    },

    removeTab(targetName) {
      let tabs = this.editableTabs;
      let activeName = this.editableTabsValue;
      if (activeName === targetName) {
        tabs.forEach((tab, index) => {
          if (tab.driverName === targetName) {
            let nextTab = tabs[index + 1] || tabs[index - 1];
            if (nextTab) {
              activeName = nextTab.driverName;
            }
          }
        });
      }

      this.editableTabsValue = activeName;
      this.editableTabs = tabs.filter((tab) => tab.driverName !== targetName);
    },

    okNewConstruction(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          axios
            .post(this.BASE_URL + "connection/create", this.form)
            .then((dt) => {
              if (dt.data.code === "00000") {
                axios
                  .get(this.BASE_URL + "connection/list", {
                    params: this.listQuery,
                  })
                  .then((res) => {
                    this.newConstruction = false;
                    if (res.data.code === "00000") {
                      this.selectDatadialogTableVisible = true;
                      this.usableDataList = res.data.data;
                    } else {
                      this.$message.error("查询可用数据链接错误请联系开发者");
                    }
                  });
              } else {
                this.$message.error("新建链接错误请联系开发者");
              }
            });
        } else {
          return false;
        }
      });
    },

    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    handleNodeClick(data) {
      this.newConstruction = true;
      this.form.driverId = data.id;
    },
    getList() {
      axios
        .get(this.BASE_URL + "/driver/list", {
          params: this.listQuery,
        })
        .then((dt) => {
          this.treeData = dt.data.data;
        });
    },

    guide() {
      this.driver.defineSteps(steps);
      this.driver.start();
    },
  },
};
</script>
<style>
.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  padding-right: 8px;
}
</style>
<style  scoped>
.app-container {
  display: flex;
}
</style>
<style >
.el-tabs__content {
  height: 700px !important;
  max-height: 700px;
  overflow: auto;
}

.menu {
  height: 100vh;
  box-sizing: border-box;
  background-color: #333;
}

table {
  border-collapse: collapse;
  border-spacing: 0;
}

/* custom */

a {
  color: #7e8c8d;
  -webkit-backface-visibility: hidden;
  text-decoration: none;
}

li {
  list-style: none;
}

body {
  -webkit-text-size-adjust: none;
  -webkit-tap-highlight-color: rgba(0, 0, 0, 0);
}

button,
input {
  border: none;
  outline: none;
}

.el-aside {
  background-color: rebeccapurple;
}
</style>
